package com.joker.web.controller.orange;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import com.joker.common.core.domain.PageQuery;
import com.joker.common.core.domain.R;
import com.joker.common.core.page.TableDataInfo;
import com.joker.orange.domain.bo.*;
import com.joker.orange.domain.vo.*;
import com.joker.orange.service.*;
import com.joker.system.domain.SysNotice;
import com.joker.system.service.ISysNoticeService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * 首页
 *
 * @author joker
 */
@Slf4j
@RequiredArgsConstructor
@RestController
public class AppIndexController {

    private final ISysNoticeService noticeService;
    private final ICarouselImagesService carouselImagesService;
    private final IApplicationCenterService applicationCenterService;
    private final IAdvertisingSpaceService advertisingSpaceService;
    private final IVideoInfoService videoInfoService;
    private final ILongVideoCategoryService longVideoCategoryService;
    private final IStartupPageService startupPageService;
    private final IHotSearchHistoryService hotSearchHistoryService;
    private final IAdvertisingPopService advertisingPopService;

    /**
     * 广告弹窗
     */
    @PostMapping("/queryAdvertisingPopList")
    public R<List<AdvertisingPopVo>> queryAdvertisingPopList(){
        AdvertisingPopBo bo = new AdvertisingPopBo();
        bo.setIsDisplay("0");
        return R.ok(advertisingPopService.queryList(bo));
    }
    /**
     * 获取引导图
     */
    @PostMapping("/queryStartupPageList")
    public R<List<StartupPageVo>> queryStartupPageList() {
        StartupPageBo startupPageBo = new StartupPageBo();
        startupPageBo.setIsDisplay("0");
        List<StartupPageVo> list = startupPageService.queryList(startupPageBo);
        return R.ok(selectRandomItems(list, 3));
    }

    /**
     * 首页
     */
    @PostMapping("/getIndex")
    public R<Map<String, Object>> index() {
        Map<String, Object> data = new HashMap<>();
        try {
            // 公告列表
            List<SysNotice> noticeList = noticeService.selectNoticeList(new SysNotice());
            data.put("noticeList", noticeList);
            // 长视频分类
            LongVideoCategoryBo longVideoCategoryBo = new LongVideoCategoryBo();
            longVideoCategoryBo.setVisible("0");
            List<LongVideoCategoryVo> categoryList = longVideoCategoryService.queryList(longVideoCategoryBo);
            data.put("categoryList", categoryList);
            // 轮播图列表
            CarouselImagesBo imagesBo = new CarouselImagesBo();
            imagesBo.setCarouselType("0");
            imagesBo.setIsDisplay("0");
            List<CarouselImagesVo> imagesList = carouselImagesService.queryList(imagesBo);
            data.put("imagesList", imagesList);
            // 应用中心列表
            PageQuery pageQuery = new PageQuery();
            pageQuery.setPageNum(1);
            pageQuery.setPageSize(8);
            TableDataInfo<ApplicationCenterVo> tableDataInfo = applicationCenterService.queryPageList(new ApplicationCenterBo(), pageQuery);
            data.put("applicationList", tableDataInfo.getRows());
            // 首页广告
            AdvertisingSpaceBo advertisingSpaceBo = new AdvertisingSpaceBo();
            advertisingSpaceBo.setAdvertisingType("0");
            advertisingSpaceBo.setIsDisplay("0");
            List<AdvertisingSpaceVo> advertisingList = advertisingSpaceService.queryList(advertisingSpaceBo);
            data.put("advertisingList", advertisingList);
            // 底部广告
            if (advertisingList != null && advertisingList.size() >= 3) {
                data.put("bottomData", advertisingList.get(advertisingList.size() - 1));
            }
            // 精选视频
            VideoInfoBo videoInfoBo = new VideoInfoBo();
            videoInfoBo.setVideoType("0");
            videoInfoBo.setIsTop("0");
            pageQuery = new PageQuery();
            pageQuery.setPageNum(1);
            pageQuery.setPageSize(5);
            TableDataInfo<VideoInfoVo> dataInfo = videoInfoService.queryPageList(videoInfoBo, pageQuery);
            data.put("videoList", dataInfo.getRows());
            return R.ok(data);
        } catch (Exception e) {
            log.info("获取首页信息失败：{}", e.getMessage());
            return R.fail("页面开小差了，请稍等一下！");
        }
    }

    /**
     * 新增历史搜索词
     */
    @PostMapping("/insertSearchHistory")
    public R<Void> insertSearchHistory(@RequestBody JSONObject jsonObject){
        HotSearchHistoryBo hotSearchHistoryBo = new HotSearchHistoryBo();
        hotSearchHistoryBo.setSearchName(jsonObject.getStr("searchName"));
        hotSearchHistoryBo.setSearchType("1");
        hotSearchHistoryService.insertByBo(hotSearchHistoryBo);
        return R.ok();
    }

    /**
     * 获取热搜词和历史搜索记录
     */
    @PostMapping("/queryHotSearchHistoryList")
    public R<Map<String,Object>> queryHotSearchHistoryList(){
        Map<String, Object> data = new HashMap<>();
        HotSearchHistoryBo hotSearchHistoryBo = new HotSearchHistoryBo();
        hotSearchHistoryBo.setSearchType("0");
        List<HotSearchHistoryVo> hotSearchList = hotSearchHistoryService.queryList(hotSearchHistoryBo);
        data.put("hotSearchList", hotSearchList);
        hotSearchHistoryBo = new HotSearchHistoryBo();
        hotSearchHistoryBo.setSearchType("0");
        List<HotSearchHistoryVo> searchHistoryList = hotSearchHistoryService.queryList(hotSearchHistoryBo);
        data.put("searchHistoryList", searchHistoryList);
        return R.ok(data);
    }

    /**
     * 清空历史搜索
     */
    @PostMapping("/deleteSearchHistory")
    public R<Void> deleteSearchHistory(){
        hotSearchHistoryService.deleteSearchHistory();
        return R.ok();
    }

    /**
     * 换一批
     */
    @PostMapping("/changeBatchList")
    public R<List<VideoInfoVo>> changeBatchList() {
        VideoInfoBo videoInfoBo = new VideoInfoBo();
        videoInfoBo.setVideoType("0");
        List<VideoInfoVo> videoInfoList = videoInfoService.queryList(videoInfoBo);
        return R.ok(videoInfoService.getRandomVideos(videoInfoList, 5));
    }

    /**
     * 根据权重匹配数据
     *
     * @param items 目标数组
     * @param count 选取条数
     * @return
     */
    public static List<StartupPageVo> selectRandomItems(List<StartupPageVo> items, int count) {
        if (items == null || items.isEmpty() || count <= 0) {
            return Collections.emptyList();
        }

        int totalWeight = items.stream().mapToInt(StartupPageVo::getDisplayWeight).sum();
        List<StartupPageVo> selectedItems = new ArrayList<>();
        Random random = new Random();

        while (selectedItems.size() < count) {
            int randomWeight = random.nextInt(totalWeight);
            int weightSum = 0;
            for (StartupPageVo item : items) {
                weightSum += item.getDisplayWeight();
                if (randomWeight < weightSum) {
                    if (!selectedItems.contains(item)) {
                        selectedItems.add(item);
                        break;
                    }
                }
            }
            // 如果已选满，则跳出循环
            if (selectedItems.size() == count) {
                break;
            }
            // 如果有权重为0的条目且尚未选满，则特殊处理
            if (ObjectUtil.equals(totalWeight, 0)) {
                for (int i = 0; i < items.size() && selectedItems.size() < count; i++) {
                    selectedItems.add(items.get(i));
                }
                break;
            }
        }

        return selectedItems;
    }

}
